<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-900">
    <div class="w-full max-w-md">
      <div class="bg-gray-800 rounded-lg shadow-xl p-8">
        <h2 class="text-3xl font-bold text-center text-white mb-8">注册</h2>

        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          @submit.prevent
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              size="large"
              prefix-icon="Message"
            />
          </el-form-item>

          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              size="large"
              prefix-icon="Phone"
            />
          </el-form-item>

          <el-form-item prop="code" v-if="captchaEnabled">
            <el-row :gutter="20">
              <el-col :span="16">
                <el-input
                  v-model="registerForm.code"
                  placeholder="请输入验证码"
                  size="large"
                />
              </el-col>
              <el-col :span="8">
                <img
                  :src="captchaUrl"
                  @click="getCaptcha"
                  class="cursor-pointer h-[40px] w-full"
                  alt="验证码"
                />
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item prop="agree">
            <el-checkbox v-model="registerForm.agree">
              我已阅读并同意
              <NuxtLink to="/protocol" class="text-green-400 hover:text-green-300">
                用户协议
              </NuxtLink>
              和
              <NuxtLink to="/policies" class="text-green-400 hover:text-green-300">
                隐私政策
              </NuxtLink>
            </el-checkbox>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="w-full"
              :loading="loading"
              @click="handleRegister"
            >
              注 册
            </el-button>
          </el-form-item>

          <div class="text-center text-gray-400">
            已有账号？
            <NuxtLink to="/login" class="text-green-400 hover:text-green-300">
              立即登录
            </NuxtLink>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const siteConfig = useSiteConfig()

// SEO设置
useSeoMeta({
  title: '注册',
  description: `注册${siteConfig.siteName}账号`
})

const registerFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaEnabled = ref(false)
const captchaUrl = ref('')

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  code: '',
  uuid: '',
  agree: false
})

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validateAgree = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请同意用户协议'))
  } else {
    callback()
  }
}

const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  agree: [
    { required: true, validator: validateAgree, trigger: 'change' }
  ]
}

// 获取验证码
const getCaptcha = async () => {
  const { data } = await $fetch('/dev-api/captchaImage')
  if (data.value) {
    captchaEnabled.value = data.value.captchaEnabled === true
    if (captchaEnabled.value) {
      captchaUrl.value = 'data:image/gif;base64,' + data.value.img
      registerForm.uuid = data.value.uuid
    }
  }
}

// 注册
const handleRegister = async () => {
  const valid = await registerFormRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    // 调用注册接口
    await $fetch('/dev-api/register', {
      method: 'POST',
      body: {
        username: registerForm.username,
        password: registerForm.password,
        email: registerForm.email,
        phonenumber: registerForm.phone,
        code: registerForm.code,
        uuid: registerForm.uuid
      }
    })

    ElMessage.success('注册成功，请登录')
    await navigateTo('/login')
  } catch (error: any) {
    ElMessage.error(error.data?.msg || error.message || '注册失败')
    // 刷新验证码
    if (captchaEnabled.value) {
      getCaptcha()
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 获取验证码
  getCaptcha()
})
</script>

<style scoped>
:deep(.el-input__wrapper) {
  background-color: rgba(31, 41, 55, 0.5);
}

:deep(.el-input__inner) {
  color: white;
}
</style>